package com.crazy.web.config.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.File;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/12/7 14:50
 */
public class CosUtil {
    private String appId;
    private String secretId;
    private String secretKey;
    private String regionStr;
    private String bucketName;
    private COSClient cosClient = null;

    /**
     *
     * @param appId
     * @param secretId
     * @param secretKey
     * @param regionStr
     * @param bucketName
     */
    public CosUtil(String appId, String secretId, String secretKey, String regionStr, String bucketName) {
        this.appId = appId;
        this.secretId = secretId;
        this.secretKey = secretKey;
        this.regionStr = regionStr;
        this.bucketName = bucketName;
    }

    /**
     * 初始化cosClient
     */
    public void setup() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(regionStr);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }

    /**
     * 上传文件
     * @param is 文件流
     * @param size 文件长度
     * @return
     */
    public String uploadImg(InputStream is, long size) {
        // 指定要上传到 COS 上对象键
        String key = UUID.randomUUID().toString();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置 Content type, 默认是 application/octet-stream
        objectMetadata.setContentType("image/jpeg");
        //文件最大为10M
        objectMetadata.setContentLength(size);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName+"-"+appId
                , key, is, objectMetadata);
        //上传速度
        putObjectRequest.setTrafficLimit(1024*1024*1);
        PutObjectResult putObjectResult  = cosClient.putObject(putObjectRequest);
        return "https://"+bucketName+"-"+appId+".cos."+regionStr+".myqcloud.com/"+key;
    }

    public void shutdown() {
        cosClient.shutdown();
    }

}
